<template>
  <el-drawer :model-value="visible" size="520px" :with-header="true" @close="onClose">
    <template #header>
      <div class="drawer-header">
        <span class="node-icon" v-if="nodeIconUnicode" :style="{ color: nodeIconColor }">{{ nodeIconUnicode }}</span>
        <span class="title">{{ nodeTypeLabel }} 配置</span>
      </div>
    </template>

    <div class="drawer-body">
      <el-form :model="form" label-position="left" class="name-form">
        <el-form-item label="名称">
          <el-input v-model="form.name" maxlength="10" placeholder="请输入名称（最多10字）" />
        </el-form-item>
        <div class="section">
          <div class="section-header">
            <span>输入字段</span>
            <el-button type="primary" link @click="addField">新增</el-button>
          </div>
          <div class="field-list">
            <div v-for="(item, index) in form.inputs" :key="index" class="field-row">
              <div class="field-name">
                <el-input v-model="item.label" :disabled="item.builtIn" placeholder="显示名称" />
              </div>
              <div class="field-type">
                <el-select v-model="item.type" placeholder="类型" style="width: 120px">
                  <el-option v-for="opt in typeOptions" :key="opt" :label="opt" :value="opt" />
                </el-select>
              </div>
              <div class="field-required">
                <el-switch v-model="item.required" active-text="必填" inactive-text="可选" inline-prompt />
              </div>
              <div class="field-actions">
                <el-button v-if="!item.builtIn" circle size="small" type="danger" class="del-btn" @click="removeField(index)">
                  <el-icon><Close /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </el-form>
    </div>
  </el-drawer>
</template>

<script>
import { defineComponent, reactive, watch, computed } from 'vue'
import { componentRegistry } from '@/components/WorkFlow/core/ComponentRegistry'
import { Close } from '@element-plus/icons-vue'

export default defineComponent({
  name: 'NodeDrawer',
  components: { Close },
  props: {
    visible: { type: Boolean, default: false },
    nodeData: { type: Object, default: null }
  },
  emits: ['save', 'close'],
  setup(props, { emit }) {
    const form = reactive({ name: '', inputs: [] })

    const typeOptions = [
      'String',
      'Number',
      'Boolean',
      'Array',
      'Object',
      'File',
      'Array[File]'
    ]

    const nodeTypeLabel = computed(() => {
      const t = props.nodeData?.type || ''
      switch (t) {
        case 'start':
          return '开始'
        case 'api':
          return 'API工具'
        case 'code':
          return '代码工具'
        case 'llm':
          return 'LLM'
        case 'aggregation':
          return '数据聚合'
        case 'loop':
          return '循环'
        case 'end':
          return '结束'
        default:
          return '节点'
      }
    })

    /**
     * 获取节点类型的图标 unicode
     * @returns {string}
     */
    const nodeIconUnicode = computed(() => {
      const t = props.nodeData?.type
      const cfg = t ? componentRegistry.getNodeConfig(t) : null
      return cfg?.iconUnicode || ''
    })

    /**
     * 获取节点类型图标颜色（优先取节点数据中的 color）
     * @returns {string}
     */
    const nodeIconColor = computed(() => {
      const t = props.nodeData?.type
      const cfg = t ? componentRegistry.getNodeConfig(t) : null
      return props.nodeData?.color || cfg?.color || '#333333'
    })

    /**
     * 初始化表单数据
     * @returns {void}
     */
    const initForm = () => {
      const d = props.nodeData || {}
      form.name = (d.name || '').toString().slice(0, 10)
      const existing = Array.isArray(d.inputs) ? d.inputs : []
      form.inputs = existing.length > 0 ? existing.map(x => ({ ...x })) : getDefaultInputs(d.type)
    }

    /**
     * 获取不同节点类型的默认输入字段
     * @param {string} type 节点类型
     * @returns {Array}
     */
    const getDefaultInputs = (type) => {
      if (type === 'start') {
        return [
          { key: 'order_id', label: 'order_id', type: 'String', required: true, builtIn: false }
        ]
      }
      return []
    }

    /**
     * 新增一个输入字段
     * @returns {void}
     */
    const addField = () => {
      form.inputs.push({ key: '', label: '', type: 'String', required: false, builtIn: false })
    }

    /**
     * 删除一个输入字段
     * @param {number} index 索引
     * @returns {void}
     */
    const removeField = (index) => {
      form.inputs.splice(index, 1)
    }

    /**
     * 保存配置并向上抛出
     * @returns {void}
     */
    /**
     * 实时保存当前表单到父组件
     * @returns {void}
     */
    const handleSave = () => {
      emit('save', { inputs: form.inputs })
    }

    const onClose = () => {
      const name = (form.name || '').toString().slice(0, 10)
      if (name) emit('save', { name })
      emit('close')
    }

    watch(() => props.nodeData, () => initForm(), { immediate: true })
    watch(() => form.inputs, () => handleSave(), { deep: true })

    return {
      form,
      typeOptions,
      nodeTypeLabel,
      addField,
      removeField,
      handleSave,
      onClose,
      nodeIconUnicode,
      nodeIconColor
    }
  }
})
</script>

<style scoped>
.drawer-header {
  display: flex;
  align-items: center;
  gap: 8px;
}
.title {
  font-size: 16px;
  font-weight: 600;
}
.node-icon {
  font-family: iconfont;
  font-size: 20px;
  line-height: 1;
}
.drawer-body {
  padding: 8px 4px 16px 4px;
}
.name-form :deep(.el-form-item__label) {
  width: auto !important;
  text-align: left;
  padding-right: 8px;
}
.section {
  margin-top: 12px;
}
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}
.field-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.field-row {
  display: grid;
  grid-template-columns: 2.4fr 1.2fr 0.8fr 44px;
  gap: 8px;
  align-items: center;
}
.field-name,
.field-type,
.field-required {
  width: 100%;
}
.del-btn {
  padding: 2px;
  height: 24px;
}
.del-btn :deep(.el-icon) {
  font-size: 14px;
}
</style>

